package com.yishusmt.wechatapi.wechatdev.utils;

import com.yishusmt.wechatapi.wechatdev.constant.EnterConstant;
import com.yishusmt.wechatapi.wechatdev.constant.OrderConstant;
import com.yishusmt.wechatapi.wechatdev.constant.RedisConstant;
import com.yishusmt.wechatapi.wechatdev.constant.UrlConstant;
import com.yishusmt.wechatapi.wechatdev.dto.request.ExpressDeliveryReq;
import com.yishusmt.wechatapi.wechatdev.dto.response.OrderRes;
import com.yishusmt.wechatapi.wechatdev.entity.*;
import com.yishusmt.wechatapi.wechatdev.mapper.*;
import com.yishusmt.wechatapi.wechatdev.service.AsyncTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * 本地消息处理
 *
 * @author zhangyi
 * @date 2018/9/1 11:46
 */
@Component
@Slf4j
public class LocalMessageUtil {

    @Autowired
    private MemberInfoMapper memberInfoMapper;

    @Autowired
    private AsyncTaskService asyncTaskService;

    @Autowired
    private MailUtil mailUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private WechatMemebrInfoMapper wechatMemebrInfoMapper;

    @Autowired
    private ReceivingAddressInfoMapper receivingAddressInfoMapper;

    @Autowired
    private PurchaserInfoMapper purchaserInfoMapper;

    @Autowired
    private SupplierInfoMapper supplierInfoMapper;

    @Autowired
    private MemberEntityMapper memberEntityMapper;

    @Autowired
    private HttpClientUtil httpClientUtil;

    @Autowired
    private RequirementInfoMapper requirementInfoMapper;

    @Autowired
    private ReceivingAddressEntityMapper receivingAddressEntityMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    /**
     * 身份验证
     *
     * @param input
     * @param openId
     */
    public String IDVerification(String input, String openId) {
        String email = input.replace(EnterConstant.EMAIL, "");
        String phone = input.replace(EnterConstant.PHONE, "");

        //本地用户存在标记
        boolean[] isLocalUser = new boolean[]{false, false, false};
        //本地用户查询
        List<String> localUser = wechatMemebrInfoMapper.selectRepeat();
        localUser.stream()
                .forEach(e -> {
                    if (e.equals(openId)) {
                        WechatMemebrEntity wechatMemebrEntity
                                = wechatMemebrInfoMapper.selectMemberByOpenId(e);
                        isLocalUser[0] = true;
                        if (wechatMemebrEntity.getPhone().equals(phone)) {
                            isLocalUser[1] = true;
                        } else if (wechatMemebrEntity.getEmail().equals(email)) {
                            isLocalUser[2] = true;
                        }

                    }
                });
        //验证格式是否正确
        if (isLocalUser[0] && (isLocalUser[1] || isLocalUser[2])) {
            return "欢迎您回来，易树制造竭诚为您服务！---";
        } else if (isLocalUser[1]) {
            return "手机号格式错误...";
        } else if (isLocalUser[2]) {
            return "邮箱格式错误...";
        }
        //本地查询用户信息目的是让openid和本地用户信息联系上规则：手机号17755810059
        boolean contains = StringUtils.contains(input, EnterConstant.EMAIL_FLAG);
        StringBuffer in = new StringBuffer();
        //用户实体
        WechatMemebrEntity wechatMemebrEntity = new WechatMemebrEntity();
        //输入实体
        InputEntity inputEntity = new InputEntity();
        if (contains) {
            wechatMemebrEntity.setEmail(email);
            inputEntity.setEmail(email);
            in.append(email);
        } else {
            wechatMemebrEntity.setPhone(phone);
            inputEntity.setMobile(phone);
            in.append(phone);
        }
        wechatMemebrEntity.setOpenid(openId);
        wechatMemebrEntity.setUpdateTime(DateUtil.getLocalDate());
        wechatMemebrEntity.setUpdateTime(DateUtil.getLocalDate());

        MemberEntity memberEntity = memberInfoMapper.selectMember(inputEntity);
        Optional<MemberEntity> memberTemp = Optional.ofNullable(memberEntity);

        if (memberTemp.isPresent()) {
            //将本地用户联系上输入账号：：您已经是我们用户了
            wechatMemebrEntity.setMemberId(memberEntity.getId());
            //用户查重标记
            boolean[] userExist = new boolean[]{true};
            List<String> openIds = wechatMemebrInfoMapper.selectRepeat();
            openIds.stream().forEach(e -> {
                if (e.equals(openId)) {
                    userExist[0] = false;
                }
            });
            if (userExist[0]) {
                boolean flag = asyncTaskService.saveUser(wechatMemebrEntity);
                if (flag) {
                    return "欢迎您：" + memberEntity.getNickName();
                } else {
                    return "对不起，保存用户失败... ...";
                }
            }
            String salt = MD5Util.encryptString(openId);
            redisUtil.set(RedisConstant.USER_TOKEN + salt,
                    AESUtil.encryptString(openId, salt),
                    new Long(1 * 60 * 60 * 24 * 30));
            return "欢迎您：" + memberEntity.getNickName();
        } else {
            //验证码
            String s = RandomUtil.randomCode();
            //检验字符串是否含有关键字符
            if (StringUtils.contains(input, EnterConstant.EMAIL)) {
                //验证邮箱格式
                boolean b = CheckInputUtil.checkEmail(email);
                if (b) {
                    log.info("发送邮箱验证码{}", email);
                    mailUtil.sendMessage(email, "易树智造", "发给您的验证码：" + s);
                    redisUtil.set(RedisConstant.CODE_TOEKN + OpenIdUtil.encodeOpenId(openId), s, 60 * 3L);
                    return "已发送您的邮箱中，请查收...";
                } else {
                    return "您填写的邮箱格式有错误::";
                }
            } else if (StringUtils.contains(input, EnterConstant.PHONE)) {
                //验证手机号格式
                boolean b = CheckInputUtil.checkMobileNumber(phone);
                if (b) {
                    log.info("发送手机验证码{}", phone);
                    AliyunSmsUtil.sendCodeSms(phone, s);
                    redisUtil.set(RedisConstant.CODE_TOEKN + OpenIdUtil.encodeOpenId(openId), s, 60 * 3L);
                    return "已发送您的手机中，请查收...";
                } else {
                    return "您填写的手机格式有错误::";
                }
            }
            return "";
        }
    }

    /**
     * 检测用户输入的验证码
     *
     * @param code
     * @param openId
     * @return
     */
    public boolean checkCode(String code, String openId) {
        //查看缓存是否有数据
        String cacheCode = redisUtil.get(RedisConstant.CODE_TOEKN + OpenIdUtil.encodeOpenId(openId));
        System.out.println("查看缓存中的数据：" + cacheCode);
        if (cacheCode != null) {
            //判断输入验证码是否一致
            if (code.equals(cacheCode)) {
                //生成用户TOKEN
                String salt = MD5Util.encryptString(openId);
                redisUtil.set(RedisConstant.USER_TOKEN + salt,
                        AESUtil.encryptString(openId, salt),
                        new Long(1 * 60 * 60 * 24 * 30));
                redisUtil.del(RedisConstant.CODE_TOEKN + OpenIdUtil.encodeOpenId(openId));
                return true;
            }
        }
        return false;
    }


    /**
     * 查询我的收货地址
     *
     * @return
     */
    public String harvestAddress(Long memberId) {
        StringBuffer resutl = new StringBuffer();
        List<ReceivingAddressEntity> addressList =
                receivingAddressInfoMapper.selectAllAddresses(memberId);
        boolean present = Optional.ofNullable(addressList).isPresent();
        AtomicInteger atomicInteger = new AtomicInteger(0);
        addressList.stream()
                .forEach(e -> {
                    int count = atomicInteger.incrementAndGet();
                    resutl.append(present ?
                            "收货地址：" + count +
                                    "\n省/市：" + e.getProvinceName() + "/" + e.getCountryName() +
                                    "\n详细收货地址：" + e.getDetailaddress() +
                                    "\n收件人：" + e.getName() +
                                    "\n收件人联系方式：" + Optional.ofNullable(e.getTelphone() == null || "null".equals(e.getTelphone()) ? null : e.getTelphone()).orElse(e.getMobile())
                            : "查询未果...");
                });
        return resutl.toString();
    }

    /**
     * 查询我的资料
     *
     * @return
     */
    public String harvestMineData(Long memberId) {
        MemberEntity memberEntity =
                memberEntityMapper.selectByPrimaryKey(memberId);
        Integer type = memberEntity.getType();
        PurchaserEntity purchaserEntity = null;
        SupplierEntity supplierEntity = null;
        if (1 == type) {
            supplierEntity =
                    supplierInfoMapper.selectSupplierByMemberId(memberId);
            return "公司名称：" + supplierEntity.getCompanyName() +
                    "\n公司邮箱：" + supplierEntity.getCompanyEmail() +
                    "\n统一社会信用码：" + purchaserEntity.getCreditCode() +
                    "\n对公账户：" + supplierEntity.getPublicAccount() +
                    "\n联系人：" + supplierEntity.getLinkMan() +
                    "\n联系人电话：" + supplierEntity.getLinkPhone() +
                    "\n联系人邮箱：" + supplierEntity.getLinkEmail() +
                    "\n法人：" + supplierEntity.getLegalPerson() +
                    "\n详细地址：" + supplierEntity.getDetailAddress();
        } else if (2 == type) {
            purchaserEntity =
                    purchaserInfoMapper.selectPurchaserByMemberId(memberId);
            return "公司名称：" + purchaserEntity.getCompanyName() +
                    "\n公司邮箱：" + purchaserEntity.getCompanyEmail() +
                    "\n统一社会信用码：" + purchaserEntity.getCreditCode() +
                    "\n联系人：" + purchaserEntity.getLinkMan() +
                    "\n联系人电话：" + purchaserEntity.getLinkPhone() +
                    "\n联系人邮箱：" + purchaserEntity.getLinkEmail() +
                    "\n法人：" + purchaserEntity.getLegalPerson() +
                    "\n详细地址：" + purchaserEntity.getDetailAddress();
        }
        return "我的资料查询失败";
    }

    /**
     * 查询我的订单
     *
     * @return
     */
    public String harvestOrder(Long memberId) {
        StringBuffer orderInfo = new StringBuffer();
        List<OrderRes> orderRes =
                orderInfoMapper.selectOrderByMemberId(memberId);
        orderRes.stream()
                .forEach(e -> {
                    //判断订单状态
                    Integer status = e.getStatus();
                    String str = "";
                    switch (status){
                        case OrderConstant.WAIT_PAY:
                            str = "您未付款";
                            break;
                        case OrderConstant.WAIT_SURE_PAY:
                            str = "审核付款金额";
                            break;
                        case OrderConstant.LINK_SUPPLIER:
                            str = "正在匹配合适的加工厂";
                            break;
                        case OrderConstant.WAIT_PRODUCT_END:
                            str = "生产中";
                            break;
                        case OrderConstant.WAIT_GOODS:
                            str = "产品已发货";
                            break;
                        case OrderConstant.WAIT_COMMENTS:
                            str = "待评价";
                            break;
                        case OrderConstant.WAIT_PAY_SUPPLIER:
                            str = "待结算金额";
                            break;
                        case OrderConstant.END:
                            str = "订单已经完成";
                            break;
                        case OrderConstant.FAIL:
                            str = "订单提交失败";
                            break;
                        case OrderConstant.APPLY_REFUND:
                            str = "退款中...";
                            break;
                        case OrderConstant.REFUND_FAIL:
                            str = "退款成功";
                            break;
                        case OrderConstant.REFUND_SUCCESS:
                            str = "退款失败";
                            break;
                        default:
                            str = "订单进行中...";
                                break;
                    }
                    String email = e.getEmail()==null?"暂无":e.getEmail();
                    String phone = e.getMobile()==null?"暂无":e.getMobile();

                    orderInfo.append("\n订单号："+e.getOrderNo())
                            .append("\n订单状态："+str)
                            .append("\n项目专员邮箱："+email)
                            .append("\n项目专员手机："+phone)
                            .append("\n-----------");
                });
        return orderInfo.toString().equals("")?"您暂时没有创建订单,快速创建：http://www.yishusmt.com":orderInfo.toString();
    }

    public static final String FAIL_TIPS = "输入格式错误" +
            "\n请输入：" +
            "\n快递+快递单号";

    /**
     * 查询我的快递
     *
     * @param trackingNumber 快递单号
     * @return
     */
    public String harvestTrackingNumber(String trackingNumber) {
        String postNumber = trackingNumber.replace(EnterConstant.POST, "");
        postNumber = postNumber.replace("\n", "")
                .replace("\t", "")
                .trim();
        if ("".equals(postNumber)) {
            return FAIL_TIPS;
        }
        //检验单号
        char[] chars = postNumber.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (!NumberUtils.isDigits(String.valueOf(chars[i]))) {
                return FAIL_TIPS;
            }
        }
        //调用第三方接口做查询
        String replace = UrlConstant.EXPRESS_INQUIRY.replace(UrlConstant.POST_FLAG, postNumber);
        ExpressDeliveryReq expressDeliveryReq = null;
        try {
            expressDeliveryReq =
                    JacksonUtil.readValue(httpClientUtil.getConnect(replace), ExpressDeliveryReq.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuffer result = new StringBuffer();
        Optional.ofNullable(expressDeliveryReq)
                .get()
                .getData().stream()
                .forEach(e -> {
                    result.append("\n时间: ").append(e.getTime())
                            .append("\n说明：").append(e.getContext())
                            .append("\n     ||").append("\n     V");
                });
        return result.toString();
    }

    /**
     * 查询发布需求
     *
     * @return
     */
    public String harvestDemand(Long memberId) {
        //返回数据
        StringBuffer result = new StringBuffer();
        List<RequirementEntity> requirementEntities = requirementInfoMapper.selectRequirementByMemberId(memberId);
        requirementEntities.stream()
                .filter(f -> f != null)
                .forEach(e -> {
                    String cl = "";
                    String endlineType = "";
                    Integer wlCl = e.getWlCl();
                    if (wlCl == 1) {
                        cl = "有铅锡膏";
                    } else if (wlCl == 2) {
                        cl = "无铅锡膏";
                    } else if (wlCl == 4) {
                        cl = "红胶";
                    } else if (wlCl == 3) {
                        cl = "有铅锡膏和无铅锡膏";
                    } else if (wlCl == 5) {
                        cl = "有铅锡膏和红胶";
                    } else if (wlCl == 6) {
                        cl = "有铅锡膏和红胶";
                    } else if (wlCl == 7) {
                        cl = "有铅锡膏和无铅锡膏和红胶";
                    }
                    Integer endlineStatus = e.getEndlineType();
                    if (endlineStatus == 1) {
                        endlineType = "普通";
                    } else if (endlineStatus == 2) {
                        endlineType = "加急";
                    }

                    String type = "";
                    Byte typeB = e.getType();
                    if (typeB.equals(1)) {
                        type = "纯贴片";
                    } else if (typeB.equals(2)) {
                        type = "贴片+插件";
                    }

                    String aoi = "";
                    Byte aoiS = e.getType();
                    if (aoiS.equals(1)) {
                        aoi = "全测";
                    } else if (aoiS.equals(2)) {
                        aoi = "抽测";
                    }
                    Long addressId = e.getAddressId();
                    ReceivingAddressEntity receivingAddressEntity =
                            receivingAddressEntityMapper.selectByPrimaryKey(addressId);
                    result.append("\n板子的数量：" + e.getWlCount())
                            .append("\n材料：" + cl)
                            .append("\n交期类型" + endlineType)
                            .append("\n贴片类型：" + type)
                            .append("\n测试：" + aoi)
//                            .append("\n发货时间："+e.getSendTime())
//                            .append("\n收货人联系方式："+e.getContactTel())
//                            .append("\n收货人地址："+receivingAddressEntity.getDetailaddress())
                            .append("\n订单创建时间：" + DateUtil.geDateStr(e.getCreateTime()))
                            .append("\n-----------------");
                });
        return result.toString();
    }

    /**
     * 所有加工厂
     *
     * @return
     */
    public String SupplierEver() {
        //验证token
        //在
        //查询
        //不再
        //验证
        return null;
    }

    /**
     * 具体加工厂
     *
     * @return
     */
    public String Supplier(String inputStr) {
        //验证token
        //在
        //查询
        //不再
        //验证
        return null;
    }

    /**
     * 平台规范（8）
     * 服务规范（9）
     * 项目管控（10）
     * 品控规则（11）
     * 合作加盟（12）
     *
     * @return
     */
    public String Supplier() {
        //验证token
        //在
        //查询
        //不再
        //验证
        return null;
    }


}
